package cn.iocoder.yudao.module.crossborder.platform.service.provider.amazon;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.crossborder.platform.controller.admin.platformmapping.vo.PlatformMappingSaveReqVO;
import cn.iocoder.yudao.module.crossborder.platform.controller.admin.platformordermapping.vo.PlatformOrderMappingSaveReqVO;
import cn.iocoder.yudao.module.crossborder.platform.controller.admin.platformproductmapping.vo.PlatformProductMappingSaveReqVO;
import cn.iocoder.yudao.module.crossborder.platform.dal.dataobject.platformmapping.PlatformMappingDO;
import cn.iocoder.yudao.module.crossborder.platform.dal.dataobject.platformordermapping.PlatformOrderMappingDO;
import cn.iocoder.yudao.module.crossborder.platform.dal.dataobject.platformproductmapping.PlatformProductMappingDO;
import cn.iocoder.yudao.module.crossborder.platform.service.platformmapping.PlatformMappingService;
import cn.iocoder.yudao.module.crossborder.platform.service.platformordermapping.PlatformOrderMappingService;
import cn.iocoder.yudao.module.crossborder.platform.service.platformproductmapping.PlatformProductMappingService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;

/**
 * Amazon数据映射服务
 * 负责Amazon平台数据与本地系统数据之间的转换映射
 *
 * @author 芋道源码
 */
@Service
@Slf4j
public class AmazonDataMappingService {

    @Resource
    private PlatformMappingService platformMappingService;
    
    @Resource
    private PlatformOrderMappingService platformOrderMappingService;
    
    @Resource
    private PlatformProductMappingService platformProductMappingService;

    private final ObjectMapper objectMapper = new ObjectMapper();
    private final DateTimeFormatter amazonDateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");

    // Amazon平台ID（需要从配置获取）
    private static final Long AMAZON_PLATFORM_ID = 1L;

    /**
     * 转换Amazon订单数据为本地订单数据
     *
     * @param amazonOrder Amazon订单数据
     * @param storeId 店铺ID
     * @return 本地订单数据
     */
    public Map<String, Object> convertAmazonOrderToLocal(Map<String, Object> amazonOrder, Long storeId) {
        log.debug("转换Amazon订单数据: orderId={}", amazonOrder.get("AmazonOrderId"));
        
        try {
            Map<String, Object> localOrder = new HashMap<>();
            
            // 基本信息映射
            localOrder.put("platformOrderId", amazonOrder.get("AmazonOrderId"));
            localOrder.put("orderNumber", generateLocalOrderNumber((String) amazonOrder.get("AmazonOrderId")));
            localOrder.put("storeId", storeId);
            localOrder.put("platformId", AMAZON_PLATFORM_ID);
            
            // 订单状态映射
            String amazonStatus = (String) amazonOrder.get("OrderStatus");
            localOrder.put("orderStatus", mapAmazonOrderStatus(amazonStatus));
            
            // 时间信息映射
            String purchaseDate = (String) amazonOrder.get("PurchaseDate");
            if (purchaseDate != null) {
                localOrder.put("orderTime", parseAmazonDateTime(purchaseDate));
            }
            
            // 金额信息映射
            @SuppressWarnings("unchecked")
            Map<String, Object> orderTotal = (Map<String, Object>) amazonOrder.get("OrderTotal");
            if (orderTotal != null) {
                localOrder.put("totalAmount", parseAmazonAmount(orderTotal));
                localOrder.put("currency", orderTotal.get("CurrencyCode"));
            }
            
            // 买家信息映射
            localOrder.put("buyerName", amazonOrder.get("BuyerName"));
            localOrder.put("buyerEmail", amazonOrder.get("BuyerEmail"));
            
            // 配送信息映射
            @SuppressWarnings("unchecked")
            Map<String, Object> shippingAddress = (Map<String, Object>) amazonOrder.get("ShippingAddress");
            if (shippingAddress != null) {
                localOrder.put("shippingAddress", convertAmazonAddress(shippingAddress));
            }
            
            // 履约渠道映射
            String fulfillmentChannel = (String) amazonOrder.get("FulfillmentChannel");
            localOrder.put("fulfillmentType", mapAmazonFulfillmentChannel(fulfillmentChannel));
            
            // 销售渠道映射
            String salesChannel = (String) amazonOrder.get("SalesChannel");
            localOrder.put("salesChannel", salesChannel);
            
            // 市场信息
            localOrder.put("marketplaceId", amazonOrder.get("MarketplaceId"));
            
            return localOrder;
            
        } catch (Exception e) {
            log.error("转换Amazon订单数据失败: orderId={}", amazonOrder.get("AmazonOrderId"), e);
            throw new RuntimeException("转换Amazon订单数据失败", e);
        }
    }

    /**
     * 转换Amazon商品数据为本地商品数据
     *
     * @param amazonProduct Amazon商品数据
     * @param storeId 店铺ID
     * @return 本地商品数据
     */
    public Map<String, Object> convertAmazonProductToLocal(Map<String, Object> amazonProduct, Long storeId) {
        log.debug("转换Amazon商品数据: asin={}", amazonProduct.get("Asin"));
        
        try {
            Map<String, Object> localProduct = new HashMap<>();
            
            // 基本信息映射
            localProduct.put("platformProductId", amazonProduct.get("Asin"));
            localProduct.put("platformSku", amazonProduct.get("SellerSku"));
            localProduct.put("storeId", storeId);
            localProduct.put("platformId", AMAZON_PLATFORM_ID);
            
            // 商品标识信息
            @SuppressWarnings("unchecked")
            Map<String, Object> identifiers = (Map<String, Object>) amazonProduct.get("Identifiers");
            if (identifiers != null) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> marketplaceAsins = (List<Map<String, Object>>) identifiers.get("MarketplaceASIN");
                if (marketplaceAsins != null && !marketplaceAsins.isEmpty()) {
                    localProduct.put("asin", marketplaceAsins.get(0).get("ASIN"));
                    localProduct.put("marketplaceId", marketplaceAsins.get(0).get("MarketplaceId"));
                }
            }
            
            // 商品属性映射
            @SuppressWarnings("unchecked")
            Map<String, Object> attributes = (Map<String, Object>) amazonProduct.get("AttributeSets");
            if (attributes != null) {
                localProduct.put("productName", extractProductTitle(attributes));
                localProduct.put("brand", extractProductBrand(attributes));
                localProduct.put("description", extractProductDescription(attributes));
                localProduct.put("category", extractProductCategory(attributes));
            }
            
            // 销售信息映射
            @SuppressWarnings("unchecked")
            Map<String, Object> salesRankings = (Map<String, Object>) amazonProduct.get("SalesRankings");
            if (salesRankings != null) {
                localProduct.put("salesRank", extractSalesRank(salesRankings));
            }
            
            // 关系映射
            @SuppressWarnings("unchecked")
            Map<String, Object> relationships = (Map<String, Object>) amazonProduct.get("Relationships");
            if (relationships != null) {
                localProduct.put("parentAsin", extractParentAsin(relationships));
                localProduct.put("variations", extractVariations(relationships));
            }
            
            return localProduct;
            
        } catch (Exception e) {
            log.error("转换Amazon商品数据失败: asin={}", amazonProduct.get("Asin"), e);
            throw new RuntimeException("转换Amazon商品数据失败", e);
        }
    }

    /**
     * 转换Amazon库存数据为本地库存数据
     *
     * @param amazonInventory Amazon库存数据
     * @param storeId 店铺ID
     * @return 本地库存数据
     */
    public Map<String, Object> convertAmazonInventoryToLocal(Map<String, Object> amazonInventory, Long storeId) {
        log.debug("转换Amazon库存数据: asin={}", amazonInventory.get("Asin"));
        
        try {
            Map<String, Object> localInventory = new HashMap<>();
            
            // 基本信息映射
            localInventory.put("platformProductId", amazonInventory.get("Asin"));
            localInventory.put("platformSku", amazonInventory.get("SellerSku"));
            localInventory.put("storeId", storeId);
            localInventory.put("platformId", AMAZON_PLATFORM_ID);
            
            // 库存数量映射
            localInventory.put("totalQuantity", amazonInventory.get("TotalQuantity"));
            localInventory.put("availableQuantity", amazonInventory.get("InStockQuantity"));
            localInventory.put("reservedQuantity", amazonInventory.get("ReservedQuantity"));
            localInventory.put("inboundQuantity", amazonInventory.get("InboundQuantity"));
            
            // 库存状态映射
            String condition = (String) amazonInventory.get("Condition");
            localInventory.put("condition", mapAmazonCondition(condition));
            
            // 履约中心信息
            localInventory.put("fulfillmentCenterId", amazonInventory.get("FulfillmentCenterId"));
            
            // 最后更新时间
            String lastUpdated = (String) amazonInventory.get("LastUpdatedTime");
            if (lastUpdated != null) {
                localInventory.put("lastUpdatedTime", parseAmazonDateTime(lastUpdated));
            }
            
            return localInventory;
            
        } catch (Exception e) {
            log.error("转换Amazon库存数据失败: asin={}", amazonInventory.get("Asin"), e);
            throw new RuntimeException("转换Amazon库存数据失败", e);
        }
    }

    /**
     * 创建订单映射关系
     *
     * @param localOrderId 本地订单ID
     * @param amazonOrderId Amazon订单ID
     * @param storeId 店铺ID
     * @return 映射ID
     */
    public Long createOrderMapping(Long localOrderId, String amazonOrderId, Long storeId) {
        try {
            PlatformOrderMappingSaveReqVO mappingReqVO = new PlatformOrderMappingSaveReqVO();
            mappingReqVO.setPlatformId(AMAZON_PLATFORM_ID);
            mappingReqVO.setStoreId(storeId);
            mappingReqVO.setLocalOrderId(localOrderId);
            mappingReqVO.setPlatformOrderId(amazonOrderId);
            mappingReqVO.setMappingStatus(1); // 已映射
            mappingReqVO.setSyncStatus(2); // 同步成功
            mappingReqVO.setLastSyncTime(LocalDateTime.now());
            
            return platformOrderMappingService.createPlatformOrderMapping(mappingReqVO);
        } catch (Exception e) {
            log.error("创建订单映射关系失败: localOrderId={}, amazonOrderId={}", localOrderId, amazonOrderId, e);
            throw new RuntimeException("创建订单映射关系失败", e);
        }
    }

    /**
     * 创建商品映射关系
     *
     * @param localProductId 本地商品ID
     * @param amazonAsin Amazon ASIN
     * @param amazonSku Amazon SKU
     * @param storeId 店铺ID
     * @return 映射ID
     */
    public Long createProductMapping(Long localProductId, String amazonAsin, String amazonSku, Long storeId) {
        try {
            PlatformProductMappingSaveReqVO mappingReqVO = new PlatformProductMappingSaveReqVO();
            mappingReqVO.setPlatformId(AMAZON_PLATFORM_ID);
            mappingReqVO.setStoreId(storeId);
            mappingReqVO.setLocalProductId(localProductId);
            mappingReqVO.setPlatformProductId(amazonAsin);
            mappingReqVO.setPlatformSku(amazonSku);
            mappingReqVO.setPlatformAsin(amazonAsin);
            mappingReqVO.setMappingStatus(1); // 已映射
            mappingReqVO.setSyncStatus(2); // 同步成功
            mappingReqVO.setLastSyncTime(LocalDateTime.now());
            
            return platformProductMappingService.createPlatformProductMapping(mappingReqVO);
        } catch (Exception e) {
            log.error("创建商品映射关系失败: localProductId={}, amazonAsin={}", localProductId, amazonAsin, e);
            throw new RuntimeException("创建商品映射关系失败", e);
        }
    }

    // ==================== 私有辅助方法 ====================

    /**
     * 生成本地订单号
     */
    private String generateLocalOrderNumber(String amazonOrderId) {
        return "AMZ_" + amazonOrderId;
    }

    /**
     * 映射Amazon订单状态
     */
    private Integer mapAmazonOrderStatus(String amazonStatus) {
        if (amazonStatus == null) return 0;
        
        switch (amazonStatus.toUpperCase()) {
            case "PENDING": return 1; // 待处理
            case "UNSHIPPED": return 2; // 未发货
            case "PARTIALLYSHIPPED": return 3; // 部分发货
            case "SHIPPED": return 4; // 已发货
            case "CANCELED": return 5; // 已取消
            case "UNFULFILLABLE": return 6; // 无法履约
            default: return 0; // 未知状态
        }
    }

    /**
     * 解析Amazon日期时间
     */
    private LocalDateTime parseAmazonDateTime(String dateTimeStr) {
        try {
            return LocalDateTime.parse(dateTimeStr, amazonDateFormat);
        } catch (Exception e) {
            log.warn("解析Amazon日期时间失败: {}", dateTimeStr);
            return LocalDateTime.now();
        }
    }

    /**
     * 解析Amazon金额
     */
    private BigDecimal parseAmazonAmount(Map<String, Object> amountMap) {
        if (amountMap == null) return BigDecimal.ZERO;
        
        Object amount = amountMap.get("Amount");
        if (amount instanceof String) {
            try {
                return new BigDecimal((String) amount);
            } catch (NumberFormatException e) {
                log.warn("解析Amazon金额失败: {}", amount);
                return BigDecimal.ZERO;
            }
        } else if (amount instanceof Number) {
            return BigDecimal.valueOf(((Number) amount).doubleValue());
        }
        
        return BigDecimal.ZERO;
    }

    /**
     * 转换Amazon地址
     */
    private Map<String, Object> convertAmazonAddress(Map<String, Object> amazonAddress) {
        Map<String, Object> localAddress = new HashMap<>();
        localAddress.put("name", amazonAddress.get("Name"));
        localAddress.put("addressLine1", amazonAddress.get("AddressLine1"));
        localAddress.put("addressLine2", amazonAddress.get("AddressLine2"));
        localAddress.put("city", amazonAddress.get("City"));
        localAddress.put("stateOrRegion", amazonAddress.get("StateOrRegion"));
        localAddress.put("postalCode", amazonAddress.get("PostalCode"));
        localAddress.put("countryCode", amazonAddress.get("CountryCode"));
        localAddress.put("phone", amazonAddress.get("Phone"));
        return localAddress;
    }

    /**
     * 映射Amazon履约渠道
     */
    private String mapAmazonFulfillmentChannel(String fulfillmentChannel) {
        if ("AFN".equals(fulfillmentChannel)) {
            return "FBA"; // Amazon履约
        } else if ("MFN".equals(fulfillmentChannel)) {
            return "FBM"; // 商家履约
        }
        return "UNKNOWN";
    }

    /**
     * 映射Amazon商品状态
     */
    private String mapAmazonCondition(String condition) {
        if (condition == null) return "NEW";
        
        switch (condition.toUpperCase()) {
            case "NEW": return "NEW";
            case "USED": return "USED";
            case "COLLECTIBLE": return "COLLECTIBLE";
            case "REFURBISHED": return "REFURBISHED";
            default: return "NEW";
        }
    }

    // 商品属性提取方法（简化实现）
    private String extractProductTitle(Map<String, Object> attributes) {
        // TODO: 实现从Amazon商品属性中提取标题的逻辑
        return "Amazon Product";
    }

    private String extractProductBrand(Map<String, Object> attributes) {
        // TODO: 实现从Amazon商品属性中提取品牌的逻辑
        return "Unknown Brand";
    }

    private String extractProductDescription(Map<String, Object> attributes) {
        // TODO: 实现从Amazon商品属性中提取描述的逻辑
        return "Amazon Product Description";
    }

    private String extractProductCategory(Map<String, Object> attributes) {
        // TODO: 实现从Amazon商品属性中提取分类的逻辑
        return "Unknown Category";
    }

    private Integer extractSalesRank(Map<String, Object> salesRankings) {
        // TODO: 实现从Amazon销售排名中提取排名的逻辑
        return 0;
    }

    private String extractParentAsin(Map<String, Object> relationships) {
        // TODO: 实现从Amazon关系中提取父ASIN的逻辑
        return null;
    }

    private List<String> extractVariations(Map<String, Object> relationships) {
        // TODO: 实现从Amazon关系中提取变体的逻辑
        return new ArrayList<>();
    }
}
